package com.lzx.adx.report.controller.v1.hw;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.constant.RedisKeyConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.GtdResult;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.EventTypeEnums;
import com.lzx.adx.report.enums.HwCovertKjbTypeEnums;
import com.lzx.adx.report.enums.KsjsCovertGtdEventTypeEnums;
import com.lzx.adx.report.model.huawei.request.HwReportRequest;
import com.lzx.adx.report.model.huawei.request.HwUploadRequest;
import com.lzx.adx.report.model.tencent.request.GTdCallBackRequest;
import com.lzx.adx.report.model.tencent.request.callback.Params;
import com.lzx.adx.report.model.tencent.request.callback.UserInfo;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.HwSecureUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * 华为饿了么假回歘
 */

@RequestMapping("/hw/kjb")
@RestController
@Slf4j
public class HwKjbReportController implements Serializable {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;





    @GetMapping("/report")
    public ResponseEntity hwReqport(HwReportRequest hwReportRequest, HttpServletRequest request){
        log.info("快接收到的请求参数为{}", JsonUtils.toJsonString(hwReportRequest));
        //参数转换
        if(StringUtils.isNotBlank(hwReportRequest.getTransunique_id())){
            hwReportRequest.setRequestId(hwReportRequest.getTransunique_id());
        }



        //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(hwReportRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setEventType(hwReportRequest.getType());
        reportDTO.setExtend(JSON.toJSONString(hwReportRequest));
        reportExecutor.execute(()->{
             reportService.saveData(reportDTO);
        });

        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(hwReportRequest.getDspId());

        //2.1进行宏替换
        String resultUrl= UrlUtil.handHwKjbUrlImpUrl(accountDTO,reportDTO);
        log.info("账号为【{}】,华为-》快手极速上报，请求的URL为{}",hwReportRequest.getDspId(),resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账号为【{}】,接收华为-》快手极速上报，的情况，响应的结果为{}",hwReportRequest.getDspId(),body);
        JSONObject jsonObject=JSONObject.parseObject(body);
        //响应状态码成功
        if(jsonObject.getInteger("ret").equals(0)){
            return ResponseEntity.ok(new Result());
        }else{
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }



    /**
     * 转换数据回传回调
     * @param requestId 请求事件ID
     * @param actionType 转换类型
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId,String actionType) throws Exception {

        log.info("接收了快接包-快手极速的的回调信息，请求流水号{},回调类型为{}，回调时间{}",requestId,actionType);
        if( StringUtils.isBlank(actionType)){
            log.info("请求参数异常，event_type{}",actionType);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId",requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(actionType);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,actionType);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }



        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        log.info("快接包-快手极速 从数据库查询的数据为{}",JsonUtils.toJsonString(reportDTO));
        //2.回调渠道，调用华为回传接口
        Long conversion_time=Long.valueOf(reportDTO.getResultTime())/1000;
        HwUploadRequest hwUploadRequest=new HwUploadRequest();
        hwUploadRequest.setOaid(reportDTO.getOaid());
        hwUploadRequest.setConversion_type(HwCovertKjbTypeEnums.getHwCode(actionType));
        hwUploadRequest.setTimestamp(String.valueOf(System.currentTimeMillis()));
        hwUploadRequest.setCallback(reportDTO.getCallback());
        hwUploadRequest.setCampaign_id(reportDTO.getCampaignId());
        hwUploadRequest.setContent_id(reportDTO.getContentId());

        hwUploadRequest.setConversion_time(String.valueOf(conversion_time));
        hwUploadRequest.setTracking_enabled("1");
        String paramsBody = JsonUtils.toJsonString(hwUploadRequest);

        log.info("账号为【{}】，快接包-给华为请求的参数为{}",reportDTO.getDspId(),paramsBody);
        Map<String,String> header=new HashMap<>();
        header.put("Authorization", HwSecureUtil.buildAuthorizationHeader(paramsBody,accountDTO.getSspKey()));
        HttpRequest body = HttpUtil.createPost(accountDTO.getSspApiUrl()).addHeaders(header).body(paramsBody);
        String result = body.execute().body();
        log.info("账号为【{}】，快接包-接收华为转换响应的结果为{}",reportDTO.getDspId(),result);
        JSONObject jsonObject=JSONObject.parseObject(result);
        Integer resultCode = jsonObject.getInteger("resultCode");
        if(resultCode==0){
            return ResponseEntity.ok(new Result());
        }else{
            return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(new Result<>().error());
        }
    }



    /**
     * 是否在比例范围内
     * @param per
     * @return
     */
    private static boolean shouldIdentifyAd(Integer per) {
        Random random = new Random();
        int randomValue = random.nextInt(100); // 生成到1之间的随机数
        log.info("随机数为{}",randomValue);
        return randomValue < per;
    }





}
